﻿using ICSharpCode.SharpZipLib.Zip;

namespace ChatGpt_WebApp.Helper
{
    using ICSharpCode.SharpZipLib.Zip;
    using System.IO;

    public static class FileZip
    {
        public static MemoryStream ZipFile(string path)
        {
            MemoryStream outputStream = new MemoryStream();

            using (ZipOutputStream zipStream = new ZipOutputStream(outputStream))
            {
                zipStream.SetLevel(3); // 设置压缩级别

                // 如果是文件夹，则遍历文件夹下所有文件并添加到 ZIP 流中
                if (Directory.Exists(path))
                {
                    AddFolderToZip(zipStream, path, "");
                }
                // 如果是文件，则添加单个文件到 ZIP 流中
                else if (File.Exists(path))
                {
                    AddFileToZip(zipStream, path, "");
                }
                else
                {
                    throw new FileNotFoundException("无法找到指定的文件或文件夹", path);
                }

                zipStream.IsStreamOwner = false; // 由调用方负责关闭 outputStream
                zipStream.Finish();
            }

            outputStream.Position = 0; // 重置流位置

            return outputStream;
        }

        private static void AddFolderToZip(ZipOutputStream zipStream, string folderPath, string parentFolderName)
        {
            string folderName = Path.GetFileName(folderPath);

            // 添加当前文件夹到 ZIP 流中
            ZipEntry folderEntry = new ZipEntry(Path.Combine(parentFolderName, folderName) + "/");
            zipStream.PutNextEntry(folderEntry);
            zipStream.Flush();

            // 遍历文件夹下所有文件并添加到 ZIP 流中
            foreach (string filePath in Directory.GetFiles(folderPath))
            {
                AddFileToZip(zipStream, filePath, Path.Combine(parentFolderName, folderName));
            }

            // 遍历文件夹下所有子文件夹并递归调用 AddFolderToZip 方法
            foreach (string subFolderPath in Directory.GetDirectories(folderPath))
            {
                AddFolderToZip(zipStream, subFolderPath, Path.Combine(parentFolderName, folderName));
            }
        }

        private static void AddFileToZip(ZipOutputStream zipStream, string filePath, string parentFolderName)
        {
            string fileName = Path.GetFileName(filePath);

            // 添加当前文件到 ZIP 流中
            ZipEntry fileEntry = new ZipEntry(Path.Combine(parentFolderName, fileName));
            zipStream.PutNextEntry(fileEntry);

            // 将文件内容写入 ZIP 流中
            using (FileStream fileStream = File.OpenRead(filePath))
            {
                byte[] buffer = new byte[4096];
                int bytesRead = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    zipStream.Write(buffer, 0, bytesRead);
                }
            }

            zipStream.Flush();
            zipStream.CloseEntry();
        }
    }

}
